package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	// "github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

var (
	// flagC         string
	slog        *zap.SugaredLogger
	atomicLevel zap.AtomicLevel
	isDebug     bool
	cityName    string // 中文城市
	
)

const (
	dpHost = `https://www.dianping.com`
	dpIndexPage = `https://www.dianping.com`
	crawledDir = `crawled`
	tmpDir = `tmp`
)

func init() {
	rootCmd.PersistentFlags().BoolVarP(&isDebug, "debug", "D", false, "debug mode")
	rootCmd.PersistentFlags().StringVarP(&cityName, "city", "C", "杭州", "城市")

	// viper.BindPFlag("debug", rootCmd.PersistentFlags().Lookup("debug"))
	// viper.BindPFlag("city", rootCmd.PersistentFlags().Lookup("city"))
	// viper.BindPFlag("shop", rootCmd.PersistentFlags().Lookup("shop"))
	initLog()
}

func initLog() {
	atomicLevel = zap.NewAtomicLevel()
	c := zap.NewProductionEncoderConfig()
	c.EncodeTime = zapcore.ISO8601TimeEncoder
	c.TimeKey = "time"
	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(c),
		zapcore.AddSync(os.Stdout),
		atomicLevel)
	logger := zap.New(core, zap.AddStacktrace(zapcore.FatalLevel), zap.AddCaller())
	defer logger.Sync()
	zap.ReplaceGlobals(logger)

	// logger.Info("initlog", zap.String("name", "hhhhhh"))
	slog = zap.S()
	// slog.Infof("global SugaredLogger after %s", "of-structured")
}

var rootCmd = &cobra.Command{
	Use:              "dp",
	TraverseChildren: true,
	Short:            "dp is a crawler for dzdp",
	Long: `A Local-Use-Only Crawler built for dzdp.
                Complete documentation is available at http://dp.originforce.club`,
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		// Do Stuff Here
		fmt.Println(isDebug)
		if isDebug {
			// atomicLevel.SetLevel(zap.ErrorLevel)
			atomicLevel.SetLevel(zap.DebugLevel)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {

		slog.Debugf("hhhhhh => %s", cityLookup[cityName])
		slog.Debugf("root cmd runing... %s", cityName)
		slog.Debugf("city => %s", cityLookup[cityName])

		// for _ = range Range(10) {
		// 	fmt.Println(randOver(20, 60))
		// }

		// go Countdown(randOver(20, 30))
		// select {}

		// Countdown(t1)
	},
}

func Execute() {

	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
